package global

import (
	"encoding/json"
	"fmt"
	"os"
)

type serverGlobal struct {
	//端口
	Port uint32
	//默认打印控制台级别
	Level uint32
	//默认打印目录
	LogPath string
	//默认文件大小限制
	FileSize uint32
	//最大连接数限制
	MaxConnections uint32
	//配置目录
	ConfPath string `json:"-"`
	//配置文件名
	confFile string `json:"-"`
	//最大报文
	MaxBufLen uint32
}

var ServerGlobal serverGlobal = serverGlobal{
	Port:           8888,
	Level:          2,
	LogPath:        ".",
	FileSize:       2 * 1024 * 1024,
	MaxConnections: 10000,
	ConfPath:       ".",
	confFile:       "server.json",
	MaxBufLen:      1024,
}

func (g *serverGlobal) Init(confpath string) {
	g.ConfPath = confpath
	dstfile := fmt.Sprintf("%s/%s", g.ConfPath, g.confFile)
	f, err := os.Open(dstfile)
	if err != nil {
		g.Save()
		return
	}
	defer f.Close()

	dec := json.NewDecoder(f)
	dec.Decode(g)
}

func (g *serverGlobal) Save() {
	dstfile := fmt.Sprintf("%s/%s", g.ConfPath, g.confFile)
	f, err := os.Create(dstfile)
	if err != nil {
		return
	}
	defer f.Close()

	enc := json.NewEncoder(f)
	enc.SetIndent("", "\t")
	enc.Encode(g)
}

type clientGlobal struct {
	//地址
	Addr string
	//端口
	Port uint32
	//配置目录
	ConfPath string `json:"-"`
	//配置文件名
	confFile string `json:"-"`
}

var ClientGlobal clientGlobal = clientGlobal{
	Addr:     "127.0.0.1",
	Port:     8888,
	ConfPath: ".",
	confFile: "client.json",
}

func (g *clientGlobal) Init(confpath string) {
	g.ConfPath = confpath
	dstfile := fmt.Sprintf("%s/%s", g.ConfPath, g.confFile)
	f, err := os.Open(dstfile)
	if err != nil {
		fmt.Println("open err=", err)
		g.Save()
		return
	}
	defer f.Close()

	dec := json.NewDecoder(f)
	dec.Decode(g)
}

func (g *clientGlobal) Save() {
	dstfile := fmt.Sprintf("%s/%s", g.ConfPath, g.confFile)
	f, err := os.Create(dstfile)

	if err != nil {
		return
	}
	defer f.Close()

	enc := json.NewEncoder(f)
	enc.SetIndent("", "\t")
	enc.Encode(g)
}
